﻿using System;
using System.Collections.Generic;
using System.Text;
using HtmlAgilityPack;

namespace Cms.EntLib
{
    public class WebDataCollect
    {
        private string WebContent = "";
        private bool StripHtml = false;
        private HtmlDocument doc = null;
        public string Url = "";
        public WebDataCollect() { }
        public WebDataCollect(string _WebContent)
        {
            WebContent = _WebContent;
            doc = new HtmlDocument();
            doc.LoadHtml(WebContent);
        }
        public Dictionary<string, string> ParseData(Dictionary<string, string> DataRule)
        {
            if ((String.IsNullOrEmpty(WebContent)||doc==null) && !String.IsNullOrEmpty(Url)) {
                WebContent = Utiltiy.GetHttpData(Url);
                doc = new HtmlDocument();
                doc.LoadHtml(WebContent);
            }

            Dictionary<string, string> Result = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> key in DataRule)
            {
                string rule = key.Value;
                if (String.IsNullOrEmpty(rule))
                    continue;
                HtmlNode htmlNode = doc.DocumentNode.SelectSingleNode(rule);
                if (htmlNode != null)
                {
                    if (!StripHtml)
                        Result.Add(key.Key, htmlNode.InnerHtml);
                    else
                        Result.Add(key.Key, htmlNode.InnerText);
                }

            }
            return Result;
        }
    }
}
